//! Standalone模式Redis服务器实现

use crate::server::traits::ServerMode;
use crate::server::redis_service::{start_redis_service, stop_redis_service, RedisService};
use crate::storage::RedisServerMode;
use async_trait::async_trait;
use std::io;
use tracing::info;

/// Standalone模式Redis服务器
pub struct StandaloneServer {
    bind_addr: String,
    redis_service: Option<RedisService>,
    is_running: bool,
}

impl StandaloneServer {
    /// 创建新的Standalone服务器
    pub fn new(bind_addr: String) -> Self {
        Self {
            bind_addr,
            redis_service: None,
            is_running: false,
        }
    }
}

#[async_trait]
impl ServerMode for StandaloneServer {
    async fn start(&mut self) -> io::Result<()> {
        if self.is_running {
            return Ok(());
        }

        info!("🚀 启动Redis-rs2 Standalone模式服务器");
        info!("📍 监听地址: {}", self.bind_addr);
        
        // 直接启动Redis服务功能
        let redis_service = start_redis_service(&self.bind_addr).await?;
        self.redis_service = Some(redis_service);
        self.is_running = true;
        
        info!("✅ Standalone模式服务器启动成功");
        Ok(())
    }

    async fn stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }

        info!("🛑 停止Standalone模式服务器");
        
        if let Some(redis_service) = self.redis_service.take() {
            stop_redis_service(redis_service).await?;
        }
        
        self.is_running = false;
        info!("✅ Standalone模式服务器已停止");
        Ok(())
    }

    fn is_running(&self) -> bool {
        self.is_running
    }
    
    fn get_mode(&self) -> RedisServerMode {
        RedisServerMode::Standalone
    }
}